
package com.heimali.happyreader.core.bean;

import com.heimali.happyreader.debug.Console;

import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class NamedThreadPool {
    private Hashtable<String, ExecutorService> mPoolMap = new Hashtable<String, ExecutorService>();
    private final static Object mutex = new Object();
    private final static String Tag = "named-pool";
    private final static NamedThreadPool sInstance = new NamedThreadPool();

    public static NamedThreadPool getInstance() {
        return sInstance;
    }

    private NamedThreadPool() {

    }

    public void initPool(String name, ExecutorService pool) {
        synchronized (mutex) {
            if (mPoolMap.get(name) == null) {
                mPoolMap.put(name, pool);
            }
        }
    }

    public void destroyPool(String name) {
        ExecutorService service = mPoolMap.remove(name);
        if (service != null) {
            service.shutdownNow();
        }
    }

    public boolean hasPoolInited(String name) {
        return mPoolMap.get(name) != null;
    }

    public void initPool(String name, int threadCount) {
        synchronized (mutex) {
            if (mPoolMap.get(name) == null) {
                mPoolMap.put(name, Executors.newFixedThreadPool(threadCount));
            }
        }
    }

    public void submit(String poolName, Runnable job) {
        ExecutorService pool = mPoolMap.get(poolName);
        if (pool == null) {
            return;
        }
        pool.submit(job);
    }

    public static class NamedThreadFactor implements ThreadFactory {
        private final String name;
        private int index;

        public NamedThreadFactor(String name) {
            this.name = name;
            this.index = 0;
        }

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(name + "-" + (index++));
        }

    }
}
